package com.yuexun.beilunpatient.base;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.service.PreLoadX5Service;
import com.yuexun.beilunpatient.ui.bean.ActValue;
import com.yuexun.beilunpatient.ui.login.ui.Act_Start;
import com.yuexun.beilunpatient.ui.main.bean.PushData;
import com.yuexun.beilunpatient.ui.question.ui.Act_Question;
import com.yuexun.beilunpatient.utils.CrashHandler;

import java.util.HashMap;

/**
 * Created by chenss on 2017/6/21 0021.
 */

public class AppContext extends Application {

    private static Context appContext;
    private static AppContext instance;
    public PushAgent mPushAgent;

    public String custom;
    public static String device_token;

    public static AppContext getInstance() {
        // 这里不用判断instance是否为空
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;
        appContext = this.getApplicationContext();
        CrashHandler.create(this);

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);

//        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
//        QbSdk.initTbsSettings(map);
//        initX5();//启动预加载的服务

        initUmeng();
    }

    private void initX5() {
        Intent intent = new Intent(this, PreLoadX5Service.class);
        startService(intent);
    }

    //初始化友盟
    private void initUmeng() {
        mPushAgent = PushAgent.getInstance(this);

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                AppContext.device_token = deviceToken;
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("jx", s1);
            }
        });

        UMConfigure.setLogEnabled(true);
//        mPushAgent.setDebugMode(true);
        mPushAgent.setMuteDurationSeconds(5);
        mPushAgent.setDisplayNotificationNumber(0);

        /**
         * 开启推送
         */
        mPushAgent.enable(new IUmengCallback() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 参考集成文档的1.6.3
             * http://dev.umeng.com/push/android/integration#1_6_3
             * */
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            //自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        } else {
                            //自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        }
//                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }

            /**
             * 参考集成文档的1.6.4
             * http://dev.umeng.com/push/android/integration#1_6_4
             * */
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.build();

                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 通知栏自定义点击事件
         *
         * 该Handler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * 参考集成文档的1.6.2
         * http://dev.umeng.com/push/android/integration#1_6_2
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                custom = msg.custom;
                if (isRunningForeground(context)) {
                    turnActivity(context, msg);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(context.getApplicationContext(), Act_Start.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.getApplicationContext().startActivity(intent);
                }
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();

            }
        };
        //使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        //参考http://bbs.umeng.com/thread-11112-1-1.html
        //CustomNotificationHandler notificationClickHandler = new CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        //TODO 多包名打包时 需要配置与Manifest.xml中相同的package
        mPushAgent.setResourcePackageName("com.yuexun.beilunpatient");
    }


    private boolean isRunningForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getPackageName())) {
            return true;
        }

        return false;
    }

    private void turnActivity(Context context, UMessage msg) {
        PushData pushData = JSON.parseObject(msg.custom, PushData.class);
        if (pushData.getMsgType().equals(ActValue.Patient_Question.getNum() + "")) {
            Intent intent = new Intent(context.getApplicationContext(), Act_Question.class);
            context.getApplicationContext().startActivity(intent);
        }
        custom = "";
    }
}
